package com.stray.crawl.expr.act;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.stray.crawl.TaskContext;
import com.stray.crawl.expr.EventData;
import com.stray.crawl.expr.Express;

public class SelectImgAction extends Express {

	private final Log log = LogFactory.getLog(this.getClass());

	@Override
	protected Object doParse(EventData event) {
		Object obj = event.getObject();
		TaskContext taskContext = event.getTaskContext();
		List<String> imageUrls = new ArrayList<String>();

		try {
			Elements imgs = ((Element) obj).select("img");
			URI uri = taskContext.getUrl().toURI();

			for (Element img : imgs) {
				String attr = img.attr("src");
				if (attr != null && attr.length() > 0) {
					if (attr.startsWith("http")) {
						imageUrls.add(attr);
					} else {
						URI imgUri = uri.resolve(attr);
						imageUrls.add(imgUri.toString());
					}
				}
			}
		} catch (URISyntaxException ex) {
			log.info("Fail to select img from obj : " + obj, ex);
		}

		return obj;
	}

}
